package com.css.zfzx.sjcj.modules.yhdisaster.repository.impl;

import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.org.dept.repository.entity.DeptEntity;
import com.css.bpm.platform.org.division.repository.DivisionRepository;
import com.css.bpm.platform.org.division.repository.entity.DivisionEntity;
import com.css.bpm.platform.org.role.repository.entity.RoleEntity;
import com.css.bpm.platform.utils.PlatformSessionUtils;
import com.css.zfzx.sjcj.common.utils.PinyinUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.YhAnalysisQueryRepository;
import com.css.zfzx.sjcj.modules.yhdisaster.repository.entity.YhDisasterEntity;
import com.css.zfzx.sjcj.modules.yhdisaster.viewobjects.AnalysisQueryVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Repository;
import org.springframework.util.StringUtils;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.math.BigInteger;
import java.util.List;

@Repository
public class YhAnalysisQueryRepositoryImpl implements YhAnalysisQueryRepository {
    @PersistenceContext
    private EntityManager em;

    @Value("${role.superCode}")
    private String superCode;
    @Value("${role.provinceCode}")
    private String provinceCode;
    @Value("${role.cityCode}")
    private String cityCode;
    @Value("${role.areaCode}")
    private String areaCode;
    @Autowired
    private DivisionRepository divisionRepository;
    @Override
    public BigInteger queryCountAnalysis(AnalysisQueryVo analysisQueryVo) {
        String provinceSubfix = PinyinUtil.buildProvinceSubfix(analysisQueryVo.getProvince());
        StringBuilder sql = new StringBuilder("select count(*) from yh_disaster"+provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            whereSql.append(" and province  =:province");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            whereSql.append(" and area  =:area");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            whereSql.append(" and city =:city");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhEarthFortification())){
            whereSql.append(" and yh_earth_fortification =:yhEarthFortification ");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhEarthIntensity())){
            whereSql.append(" and yh_earth_intensity =:yhEarthIntensity");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhNowEarthQh())){
            whereSql.append(" and yh_now_earth_qh =:yhNowEarthQh ");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhFieldType())){
            whereSql.append(" and yh_field_type =:yhFieldType");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhLotType())){
            whereSql.append(" and yh_lot_type =:yhLotType");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhExistingVirus())){
            whereSql.append(" and yh_existing_virus =:yhExistingVirus");
        }
        //--------------------------
        if(!StringUtils.isEmpty(analysisQueryVo.getEvaluationResult())){
            whereSql.append(" and evaluation_result =:evaluationResult");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getSign())){
            if("1".equals(analysisQueryVo.getSign())){
                whereSql.append(" and extends1 in ('A','B')");
            }else{
                whereSql.append(" and extends1 in ('C','D','E')");
            }

        }
        //=============================
        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea=ServerUtil.isContaintRole(roles,areaCode);
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user_id =:userId");
            }
            if(containtRolePro){
                whereSql.append(" and province like :authprovince");
            }
            if(containtRoleCity){
                whereSql.append(" and city like :authcity");
            }
            if(containtRoleArea){
                whereSql.append(" and area like :autharea");
            }
        }
        Query countQuery = this.em.createNativeQuery(sql.append(whereSql).toString());
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            countQuery.setParameter("province",analysisQueryVo.getProvince());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            countQuery.setParameter("area",analysisQueryVo.getArea());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            countQuery.setParameter("city",analysisQueryVo.getCity());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhEarthFortification())){
            countQuery.setParameter("yhEarthFortification",analysisQueryVo.getYhEarthFortification());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhEarthIntensity())){
            countQuery.setParameter("yhEarthIntensity",analysisQueryVo.getYhEarthIntensity());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhNowEarthQh())){
            countQuery.setParameter("yhNowEarthQh",analysisQueryVo.getYhNowEarthQh());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhFieldType())){
            countQuery.setParameter("yhFieldType",analysisQueryVo.getYhFieldType());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhLotType())){
            countQuery.setParameter("yhLotType",analysisQueryVo.getYhLotType());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getYhExistingVirus())){
            countQuery.setParameter("yhExistingVirus",analysisQueryVo.getYhExistingVirus());
        }
        //-------------------
        if(!StringUtils.isEmpty(analysisQueryVo.getEvaluationResult())){
            countQuery.setParameter("evaluationResult",analysisQueryVo.getEvaluationResult());
        }
        //=========================
        countQuery.setParameter("type",analysisQueryVo.getType());
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                countQuery.setParameter("userId",PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if(containtRolePro){
                countQuery.setParameter("authprovince","%"+divisionName+"%");
            }
            if(containtRoleCity){
                countQuery.setParameter("authcity","%"+divisionName+"%");
            }
            if(containtRoleArea){
                countQuery.setParameter("autharea","%"+divisionName+"%");
            }
        }
        BigInteger count = (BigInteger) countQuery.getSingleResult();
        return count;
    }
    @Override
    public List<Object[]> queryCountAnalysis1(AnalysisQueryVo analysisQueryVo) {
        StringBuilder sql = new StringBuilder("select yh_earth_fortification,count(id) from yh_disaster ");
        StringBuilder whereSql = new StringBuilder(" where is_valid='1' ");
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            whereSql.append(" and province  =:province");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            whereSql.append(" and area  =:area");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            whereSql.append(" and city =:city");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getSign())){
            if("1".equals(analysisQueryVo.getSign())){
                whereSql.append(" and extends1 in ('A','B')");
            }else{
                whereSql.append(" and extends1 in ('C','D','E')");
            }

        }
        //=============================
        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and quality_result =1");
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea=ServerUtil.isContaintRole(roles,areaCode);
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user_id =:userId");
            }
            if(containtRolePro){
                whereSql.append(" and province like :authprovince");
            }
            if(containtRoleCity){
                whereSql.append(" and city like :authcity");
            }
            if(containtRoleArea){
                whereSql.append(" and area like :autharea");
            }
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            whereSql.append(" group by province,city,area,yh_earth_fortification");
        }else if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            whereSql.append(" group by province,city,yh_earth_fortification");
        }else if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            whereSql.append(" group by province,yh_earth_fortification");
        }
        Query countQuery = this.em.createNativeQuery(sql.append(whereSql).toString());
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            countQuery.setParameter("province",analysisQueryVo.getProvince());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            countQuery.setParameter("area",analysisQueryVo.getArea());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            countQuery.setParameter("city",analysisQueryVo.getCity());
        }
        //=========================
        countQuery.setParameter("type",analysisQueryVo.getType());
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                countQuery.setParameter("userId",PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if(containtRolePro){
                countQuery.setParameter("authprovince","%"+divisionName+"%");
            }
            if(containtRoleCity){
                countQuery.setParameter("authcity","%"+divisionName+"%");
            }
            if(containtRoleArea){
                countQuery.setParameter("autharea","%"+divisionName+"%");
            }
        }
        List<Object[]> list = countQuery.getResultList();
        return list;
    }

    @Override
    public List<YhDisasterEntity> queryFortificationBig(AnalysisQueryVo analysisQueryVo) {
        String provinceSubfix = PinyinUtil.buildProvinceSubfix(analysisQueryVo.getProvince());
        StringBuilder sql = new StringBuilder("select * from yh_disaster"+provinceSubfix);
        StringBuilder whereSql = new StringBuilder(" where 1=1 ");
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            whereSql.append(" and province = :province");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            whereSql.append(" and area =:area");
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            whereSql.append(" and city = :city");
        }
        String userId = PlatformSessionUtils.getUserId();
        List<RoleEntity> roles = PlatformAPI.getOrgAPI().getUserAPI().getRoles(userId);
        //是否为超级管理员
        boolean containtRole = ServerUtil.isContaintRole(roles, superCode);
        //是否为省级管理员
        boolean containtRolePro = ServerUtil.isContaintRole(roles, provinceCode);
        //是否为市级管理员
        boolean containtRoleCity = ServerUtil.isContaintRole(roles, cityCode);
        //是否为县级管理员
        boolean containtRoleArea=ServerUtil.isContaintRole(roles,areaCode);
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                whereSql.append(" and create_user_id =:userId");
            }
            if(containtRolePro){
                whereSql.append(" and province like :authProvince");
            }
            if(containtRoleCity){
                whereSql.append(" and city like :authCity");
            }
            if(containtRoleArea){
                whereSql.append(" and area like :authArea");
            }
        }
        whereSql.append(" and yh_project_type = :type");
        whereSql.append(" and is_valid = 1");
        whereSql.append(" and quality_result =1");
        Query countQuery = this.em.createNativeQuery(sql.append(whereSql).toString(), YhDisasterEntity.class);
        if(!StringUtils.isEmpty(analysisQueryVo.getProvince())){
            countQuery.setParameter("province",analysisQueryVo.getProvince());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getArea())){
            countQuery.setParameter("area",analysisQueryVo.getArea());
        }
        if(!StringUtils.isEmpty(analysisQueryVo.getCity())){
            countQuery.setParameter("city",analysisQueryVo.getCity());
        }
        if(!containtRole){
            if (!containtRolePro && !containtRoleCity && !containtRoleArea) {
                countQuery.setParameter("userId",PlatformSessionUtils.getUserId());
            }
            DeptEntity mainDept = PlatformAPI.getOrgAPI().getUserAPI().getMainDept(userId);
            String divisionId = mainDept.getDivisionId();
            DivisionEntity validDivisionById = divisionRepository.findValidDivisionById(divisionId);
            String divisionName = validDivisionById.getDivisionName();
            if(containtRolePro){
                countQuery.setParameter("authProvince","%"+divisionName+"%");
            }
            if(containtRoleCity){
                countQuery.setParameter("authCity","%"+divisionName+"%");
            }
            if(containtRoleArea){
                countQuery.setParameter("authArea","%"+divisionName+"%");
            }
        }
        countQuery.setParameter("type",analysisQueryVo.getType());
        List<YhDisasterEntity> list=countQuery.getResultList();
        return list;
    }
}
